package com.example.demo6.ui.edit;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.example.demo6.R;
import com.example.demo6.SQLite.MyDatabase;
import com.example.demo6.SQLite.User;

public class edit_personal_informationFragment extends Fragment {

    private EditText UpdateUserName, UpdateUserPhone, UpdateUserId,UpdateRegion, UpdatePassword;

    private Button UpdateBtn, CancelUpdate;
    private String currentUsername; // 当前登录用户的用户名，用于查询和更新

    public static edit_personal_informationFragment newInstance(String username) {
        edit_personal_informationFragment fragment = new edit_personal_informationFragment();
        Bundle args = new Bundle();
        args.putString("username", username);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            currentUsername = getArguments().getString("username");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_edit_personal_information, container, false);

        // 初始化视图
        UpdateUserName = view.findViewById(R.id.UpdateUserName);
        UpdateUserId = view.findViewById(R.id.UpdateUserId);
        UpdatePassword = view.findViewById(R.id.UpdatePassword);
        UpdateUserPhone = view.findViewById(R.id.UpdateUserPhone);
        UpdateRegion = view.findViewById(R.id.UpdateRegion);
        UpdateBtn = view.findViewById(R.id.LostUpdateBtn);
        CancelUpdate = view.findViewById(R.id.CancelUpdate);

        // 填充当前用户信息（假设从数据库获取）
//        loadUserInfo();
        new LoadUserInfoTask().execute();

        // 设置按钮点击监听器
        UpdateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateUserInformation();
            }
        });

        CancelUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.findNavController(v).popBackStack();
            }
        });


        return view;
    }

    private class LoadUserInfoTask extends AsyncTask<Void, Void, User> {
        @Override
        protected User doInBackground(Void... voids) {
            return MyDatabase.getInstance(requireContext()).userDao().getUserByUsername(currentUsername);
        }

        @Override
        protected void onPostExecute(User user) {
            if (user != null) {
                UpdateUserName.setText(user.getUsername());
                UpdateUserId.setText(String.valueOf(user.getUserid()));
                UpdatePassword.setText(user.getPassword());
                UpdateUserPhone.setText(String.valueOf(user.getPhone()));
                UpdateRegion.setText(user.getRegion());
            } else {
                Toast.makeText(getContext(), "加载用户信息失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void updateUserInformation() {
        // 获取用户输入的信息
        String updatedUsername = UpdateUserName.getText().toString().trim();
        String updatedUserId = UpdateUserId.getText().toString().trim();
        String updatedPassword = UpdatePassword.getText().toString().trim();
        String updatedPhone = UpdateUserPhone.getText().toString().trim();
        String updatedRegion = UpdateRegion.getText().toString().trim();

        new UpdateUserTask(updatedUsername, updatedUserId, updatedPassword, updatedPhone, updatedRegion).execute();
    }

    private class UpdateUserTask extends AsyncTask<Void, Void, Void> {
        private final String updatedUsername;
        private final String updatedUserId;
        private final String updatedPassword;
        private final String updatedPhone;
        private final String updatedRegion;

        UpdateUserTask(String updatedUsername, String updatedUserId, String updatedPassword, String updatedPhone, String updatedRegion) {
            this.updatedUsername = updatedUsername;
            this.updatedUserId = updatedUserId;
            this.updatedPassword = updatedPassword;
            this.updatedPhone = updatedPhone;
            this.updatedRegion = updatedRegion;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            MyDatabase.getInstance(requireContext()).userDao().updateUser(
                    new User(Integer.parseInt(updatedUserId),updatedUsername,updatedPassword,Integer.parseInt(updatedPhone),updatedRegion)
            );
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Toast.makeText(getContext(), "信息更新成功", Toast.LENGTH_SHORT).show();
            NavController navController = Navigation.findNavController(requireView());
            Bundle bundle=new Bundle();
            bundle.putString("username", updatedUsername);//传参
            navController.navigate(R.id.centerFragment,bundle);
        }
    }
}